package main

import (
	"fmt"
	"sync"
	"time"
)

//map管理上亿的数据，瞬间查找
//多线程需要维护线程安全

type sMap struct {
	mymap map[string]string
	*sync.RWMutex
}

var smap sMap

var done1 chan bool

func write3() {
	keys := []string{"1", "2", "3"}

	for _, k := range keys {
		smap.Lock()
		smap.mymap[k] = k
		smap.Unlock()
		time.Sleep(1 * time.Second)
	}
	done1 <- true
}

func write4() {
	keys := []string{"h1", "h2", "h3"}

	for _, k := range keys {
		smap.Lock()
		smap.mymap[k] = k
		smap.Unlock()
		time.Sleep(1 * time.Second)
	}
	done1 <- true
}

func readMap1() {
	smap.RLock()

	fmt.Println("read lock")
	// fmt.Println(smap)
	for k, v := range smap.mymap {
		fmt.Println(k, v)
	}

	smap.RUnlock()
}

func main() {
	smap = sMap{make(map[string]string), new(sync.RWMutex)}

	done1 = make(chan bool, 2)

	go write3()
	go write4()

	fmt.Println(smap)

	for {
		readMap1()

		if len(done1) == 2 {
			fmt.Println(smap)
			break
		} else {
			time.Sleep(1 * time.Second)
		}
	}

}
